using System;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace RGuang.Kit
{
    public static class RSAKit
    {
        // 异步生成RSA密钥对
        public static async Task<(string PublicKey, string PrivateKey)> GenerateKeyPairAsync()
        {
            using (var rsa = new RSACryptoServiceProvider(2048))
            {
                // 模拟异步操作
                await Task.Yield();
                return (rsa.ToXmlString(false), rsa.ToXmlString(true));
            }
        }

        // 异步使用公钥加密数据
        public static async Task<string> EncryptAsync(string publicKey, string data)
        {
            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(publicKey);
                var dataBytes = Encoding.UTF8.GetBytes(data);
                var encryptedBytes = await Task.Run(() => rsa.Encrypt(dataBytes, false));
                return Convert.ToBase64String(encryptedBytes);
            }
        }

        // 异步使用私钥解密数据
        public static async Task<string> DecryptAsync(string privateKey, string encryptedData)
        {
            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(privateKey);
                var encryptedBytes = Convert.FromBase64String(encryptedData);
                var decryptedBytes = await Task.Run(() => rsa.Decrypt(encryptedBytes, false));
                return Encoding.UTF8.GetString(decryptedBytes);
            }
        }
    }



}

